package com.ruoyi.web.controller.nav;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.NavUserKey;
import com.ruoyi.system.service.INavUserKeyService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 密钥列表Controller
 * 
 * @author ZouYangMing
 * @date 2022-10-17
 */
@RestController
@RequestMapping("/navigation/secretkey")
public class NavUserKeyController extends BaseController
{
    @Autowired
    private INavUserKeyService navUserKeyService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询密钥列表列表
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:list')")
    @GetMapping("/list")
    public TableDataInfo list(NavUserKey navUserKey)
    {
        startPage();
        List<NavUserKey> list = navUserKeyService.selectNavUserKeyList(navUserKey);
        return getDataTable(list);
    }

    /**
     * 导出密钥列表列表
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:export')")
    @Log(title = "密钥列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NavUserKey navUserKey)
    {
        List<NavUserKey> list = navUserKeyService.selectNavUserKeyList(navUserKey);
        ExcelUtil<NavUserKey> util = new ExcelUtil<NavUserKey>(NavUserKey.class);
        util.exportExcel(response, list, "密钥列表数据");
    }

    /**
     * 获取密钥列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(navUserKeyService.selectNavUserKeyById(id));
    }

    /**
     * 新增密钥列表
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:add')")
    @Log(title = "密钥列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody NavUserKey navUserKey)
    {
        if(userService.selectUserByUserName(navUserKey.getUserName()) == null){
            return error(navUserKey.getUserName() + " 用户不存在");
        }
        if(navUserKeyService.selectNavUserKeyByKey(navUserKey.getKeyNumber()) != null){
            return error(navUserKey.getKeyNumber() + " 密钥重复，请重新输入密钥");
        }
        NavUserKey navUserKey1 = new NavUserKey();
        navUserKey1.setUserName(navUserKey.getUserName());
        List<NavUserKey> navUserKeys = navUserKeyService.selectNavUserKeyList(navUserKey1);
        if(navUserKeys.size() > 0){ //密钥已存在则执行
            if(navUserKey.getUserName().equals(navUserKeys.get(0).getUserName())){ // 用户是否存在
                return error(navUserKey.getUserName() + " 用户已有密钥");
            }
        }
        return toAjax(navUserKeyService.insertNavUserKey(navUserKey));
    }

    /**
     * 生成随机不重复的密钥
     */
    @GetMapping("/random")
    public AjaxResult random()
    {
        //如果已经存在则删除
        NavUserKey userKey = navUserKeyService.selectNavUserKeyByUserName(getLoginUser().getUsername());
        if(userKey != null){
            navUserKeyService.deleteNavUserKeyById(userKey.getId());
        }
        //生成随机不重复的密钥
        String key = RandomStringUtils.randomAlphanumeric(16);
        NavUserKey navUserKey = new NavUserKey();
        navUserKey.setUserName(getLoginUser().getUsername());
        //判断是否重复，重复则重新生成
        while (navUserKeyService.selectNavUserKeyByKey(key) != null){
            key = RandomStringUtils.randomAlphanumeric(16);
        }
        navUserKey.setKeyNumber(key);
        navUserKeyService.insertNavUserKey(navUserKey);
        return success(key);
    }

    /**
     * 修改密钥列表
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:edit')")
    @Log(title = "密钥列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody NavUserKey navUserKey)
    {
        if(userService.selectUserByUserName(navUserKey.getUserName()) == null){
            return error("用户不存在");
        }
        if(navUserKeyService.selectNavUserKeyByKey(navUserKey.getKeyNumber()) != null){
            return error("密钥已存在");
        }
        NavUserKey navUserKey1 = new NavUserKey();
        navUserKey1.setUserName(navUserKey.getUserName());
        List<NavUserKey> navUserKeys = navUserKeyService.selectNavUserKeyList(navUserKey1);
        if(navUserKeys.size() > 0){
            //密钥已存在
            if(navUserKey.getUserName().equals(navUserKeys.get(0).getUserName())){
                //密钥已存在，且是当前用户
                return toAjax(navUserKeyService.updateNavUserKey(navUserKey));
            }
            return error("用户已存在该密钥");
        }
        return toAjax(navUserKeyService.updateNavUserKey(navUserKey));
    }

    /**
     * 删除密钥列表
     */
    @PreAuthorize("@ss.hasPermi('navigation:secretkey:remove')")
    @Log(title = "密钥列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(navUserKeyService.deleteNavUserKeyByIds(ids));
    }
}
